<?php

namespace app\admin\server\entity;

use app\admin\model\entity\EntityVoiceModel;
use app\admin\ServerBase;
use app\admin\validate\entity\EntityVoiceValidate;
use think\db\exception\DbException;
use think\Request;

class EntityVoiceServer extends ServerBase
{
    protected $model;
    protected $request;
    /**
     * @var mixed
     */
    protected $param;
    /**
     * @var mixed
     */
    protected $validate;

    function __construct(Request $request)
    {
        $this->request = $request;
        $this->param = $request->param();
        $this->model = new EntityVoiceModel();
        $this->validate = new EntityVoiceValidate();
    }


    function add()
    {
        $post = $this->request->post();
        $post['musics'] = implode(',',$post['musics']);
        if (!$this->validate->scene('create')->check($post)) {
            $this->ERROR = $this->validate->getError();
            return false;
        }
        try {
            $this->model->save($post);
            $this->getMessageCode('adminMessage.success.insert', 2);
            return true;
        } catch (\Error $error) {
            $this->ERROR = $error->getMessage();
            return false;
        } catch (DbException $dbException) {
            $this->ERROR = $dbException->getMessage();
            return false;
        }
    }

    function edit()
    {
        $id = $this->request->param('id', 0);
        $post = $this->request->post();
        $post['musics'] = implode(',',$post['musics']);
        $post['id'] = $id;
        if (!$this->validate->scene('update')->check($post)) {
            $this->ERROR = $this->validate->getError();
            return false;
        }
        $info = $this->model->getFindById($id);
        if (empty($info)) {
            $this->getMessageCode('adminMessage.error.update', 1);
            return false;
        }
        if ($info->save($post)) {
            $this->getMessageCode('adminMessage.success.update', 2);
            return true;
        } else {
            $this->getMessageCode('adminMessage.error.update', 1);
            return false;
        }
    }

    function getDetail()
    {
        $info = $this->model->getFindById($this->request->param('id'));
        $this->getMessageCode('adminMessage.success.select', 2);
        return $info;
    }
}